<?php

use Nette\Application\UI\Control,
	Nette\Application\UI\Form;

class Comment extends Control {
  
  private $privatePresenter;
  private $sourceTypeId;
  private $sourceMixedId;
  private $limit;
  private $offset;
  
  /**
   * 
   * @param type $sourceTypeId - id pro typ commentare - napr video, novinka atd
   * @param type $sourceMixedId - konkretni id videa nebo novinky, ke ktere se comment vztahuje
   */
  public function init($presenter, $sourceTypeId, $sourceMixedId, $perPage = 4){
    $this->sourceTypeId = $sourceTypeId;
    $this->sourceMixedId = $sourceMixedId;
    $this->privatePresenter = $presenter;
    $this->offset = 0;
    $this->limit = $perPage;
  }

	public function createComponentCommentForm() {
		$form = new Form();
		$form->addTextArea('text', 'Komentář:')->addRule(Form::FILLED, 'Něco nám napište');
                
    $form->addSubmit('send', 'Poslat');
		$form->onSuccess[] = callback($this, 'submitCommentForm');

		return $form;
	}

	public function submitCommentForm(Form $form) {
    if($this->presenter->isAjax() && $this->presenter->getUser()->isLoggedIn()){
      $text = $form->getValues()['text'];
      
      if(!$form->isValid()){
        $form->addError('Něco nám napište');
        $this->invalidateControl('comment');
      }
      
      $userId = $this->presenter->getUser()->getId();
      $commentPublished = date('Y-m-d H:i:s', time());
      
      $this->presenter->context->createComments()->insert(array(
          'mixed_source_id' => $this->sourceMixedId,
          'type_source_id' => $this->sourceTypeId,
          'text' => $text,
          'comment_published' => $commentPublished,
          'user_id' => $userId
      ));
      
      $form->setValues(array('text' => ''), TRUE);
      $this->invalidateControl('comment');
    }
	}
  
  public function handlePage($offset){
    if($offset < 0){
      $offset = 0;
    }
    $this->offset = $offset;
    
    if($this->presenter->isAjax()){
      $this->invalidateControl('comment');
    }
  }

	public function render() {
    $allComments = $this->privatePresenter->context->createComments()
        ->where('type_source_id', $this->sourceTypeId)
        ->where('mixed_source_id', $this->sourceMixedId);
    
    $commentsCount = count($allComments);
    
    $pagesTotal = floor($commentsCount / $this->limit);
    $currentPage = floor($this->offset / $this->limit);
    
    $comments = $allComments->order('comment_published DESC')->limit($this->offset . ", ". $this->limit);
    
		$template = $this->template;
		$template->setFile(__DIR__ . '/comment.latte');
    $template->comments = $comments;
    $this->template->offset = $this->offset;
    $this->template->limit = $this->limit;
    $this->template->commentsCount = $commentsCount;
    $this->template->pagesTotal = $pagesTotal;
    $this->template->currentPage = $currentPage;
    
		$template->render();
	}

}
